<?php

namespace app\admin\services;

use app\admin\model\AdminModel;
use app\admin\model\OrderInModel;
use app\admin\model\ShopModel;
use Vtiful\Kernel\Excel;

class ExcelOrderService extends BaseService
{
    /**
     * 后台运行的导出excel任务
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function excelRunInBackground($id)
    {
        ini_set("memory_limit", "4096M");
        set_time_limit(0);
        if ($id) {
            $info = ExportMissionModel::find($id);
        } else {
            $info = ExportMissionModel::where('status', 0)->find();
        }
        if ($info) {
            switch ($info->title) {
                case '整理订单':
                    $list = self::orderList($info->params);
                    $shopList = self::getShopsById();
                    $fileName = self::makeExcel($list, $shopList, false);
                    break;
                case '售后订单':
                    $list = RefundService::orderList($info->params);
                    $fileName = RefundService::makeExcel($list, false);
                    break;
                default:
                    $list = ExpressService::orderList($info->params);
                    $fileName = ExpressService::makeExcel($list['list'], false);
            }

            $info->file = $fileName;
            $info->status = 1;
            $info->save();
        }
    }

    /**
     * 即刻导出excel
     * @param $p get过滤参数
     * @return void
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public static function excel($p, $download = true)
    {
        ini_set("memory_limit", "4096M");
        set_time_limit(0);
        $list = self::orderList($p);
        self::makeExcel($list, $download);
//        $data=[
//            //数据源
//            self::excelOrgin($list),
//            //整理订单
//            self::organizeOrder($list,$shopList),
//        ];
//        ExcelService::makeExcelWithMoreSheet($data,'订单列表');
    }

    /**
     * 根据请求参数获取原始数据
     * @param $p
     * @return mixed
     */
    public static function orderList($p)
    {
        $field = '*';
        $list = OrderInModel::where(OrderService::getListCondition($p))->field($field)->order('create_time desc');
//        if (!empty($p['productCount'])) {
//            if($p['productCount']==2)
//                //核单
//                $list = $list->whereRaw('JSON_LENGTH(product_infos) >= '.$p['productCount'].' or status = 700');
//            else
//                //有效订单
//                $list = $list->whereRaw('JSON_LENGTH(product_infos) = '.$p['productCount'].' and status <> 700');
//        }
        return $list->cursor();
//        return  OrderInModel::getList($params)->toArray();
    }

    /**
     * 导出excel
     * @param $data
     * @param $shopList
     * @return void
     */
    protected static function makeExcel($data, $download)
    {
        $config = [
//            'path' => self::getTmpDir() . '/',
            'path' => app()->getRootPath() . 'public/static/upload/order'
        ];

        $fileName = time() . rand(0, 500) . '.xlsx';

        $xlsxObject = new Excel($config);

        // 数据源
        $res = self::getOriginData($data);
        $fileObject = $xlsxObject->fileName($fileName, '数据源');
        $fileObject = $fileObject->header($res['title']);
        $fileObject = $fileObject->data($res['origin']);
        // Outptu
        $filePath = $fileObject->output();

        if ($download) {
            // Set Header
            header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Content-Length: ' . filesize($filePath));
            header('Content-Transfer-Encoding: binary');
            header('Cache-Control: must-revalidate');
            header('Cache-Control: max-age=0');
            header('Pragma: public');

            ob_clean();
            flush();

            if (copy($filePath, 'php://output') === false) {
                // Throw exception
            }

            // Delete temporary file
            @unlink($filePath);
        } else {
            return 'order/' . $fileName;
        }
    }

    /**
     * 获取文件临时路径
     * @return string
     */
    protected static function getTmpDir(): string
    {
        $tmp = ini_get('upload_tmp_dir');

        if ($tmp !== False && file_exists($tmp)) {
            return realpath($tmp);
        }

        return realpath(sys_get_temp_dir());
    }

    /**
     * 订单导出-获取源数据
     * @param $data 订单表查询获取的游标数据
     * @param $shopList 店铺列表
     * @return array
     */
    protected static function getOriginData($data)
    {

        $shopList=ShopModel::column('name','id');
        $adminList=AdminModel::column('nickname','id');
        $orgin = [];
        $title = [
            '总计金额',
            '回收单价',
            '上门地址',
            '重量预估',
            '联系电话',
            '订单状态',
            '下单时间',
            '接单时间',
            '完成时间',
            '下单人昵称',
            '回收手机数量',
            '实际重量',
            '距离',
            '上门方式',
            '物流回收点',
            '回收员',
            '回收站名称'
        ];
        foreach ($data as $i) {
            $item = $i->toArray();
            $orgin[]=[
                $item['total_amount'],
                $item['unit_price'],
                $item['address'],
                $item['weight'],
                $item['phone'],
                $item['status'],
                $item['create_time'],
                $item['accept_time'],
                $item['finish_time'],
                $item['nickname'],
                $item['phone_count'],
                $item['realweight'],
                $item['distance'],
            ];
        }
        return ['title' => $title, 'origin' => $orgin];
    }

}
